package com.firmboy.thread.proCon;

import java.util.ArrayList;

/**
 * 盘子测试类
 *
 * @author firmboy
 * @create 2018-05-17 下午4:51
 **/
public class Plate {

    private ArrayList eggs = new ArrayList();

    public synchronized Object getEgg(){
        while(eggs.size()==0){
            try{
                wait();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        Object egg = eggs.get(0);
        eggs.clear();
        notifyAll();
        System.out.println("拿到鸡蛋");
        return egg;
    }

    public synchronized void putEgg(Object egg){
        while (eggs.size()>0){
            try{
                wait();
            }catch(Exception e){
                e.printStackTrace();
            }

        }
        eggs.add(egg);
        System.out.println("放入鸡蛋");
        notifyAll();
    }

    static class AddThread implements Runnable{

        private Plate plate;

        private Object egg = new Object();

        AddThread(Plate plate){
            this.plate = plate;
        }

        @Override
        public void run() {
            plate.putEgg(egg);
        }
    }

    static class GetThread implements Runnable{
        private Plate plate;

        GetThread(Plate plate){
            this.plate = plate;
        }


        @Override
        public void run() {
            plate.getEgg();
        }
    }

    public static void main(String[] args){
        Plate plate = new Plate();

        for (int i=0;i<10;i++){
            new Thread(new AddThread(plate)).start();
            new Thread(new GetThread(plate)).start();
        }
    }


}
